# -*- coding: UTF-8 -*-
import socket
import sys
import time

import pandas as pd


def send_image_to_master(image_data, master_host, master_port):
    try:
        # 创建 TCP 套接字
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 连接到 Master 节点
        client_socket.connect((master_host, master_port))
        client_socket.sendall(b'Client')
        # 避免将长度数据一起被接收
        time.sleep(1)

        # 发送图片数据长度
        data_length = len(image_data)
        print('data len: ', data_length)
        client_socket.sendall(str(data_length).encode())

        # 等待 Master 确认接收长度信息
        client_socket.recv(1024)

        # 发送实际图片数据
        client_socket.sendall(image_data)

        # 接收处理结果
        res = client_socket.recv(1024)
        print('res: ', res.decode())

    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        client_socket.close()


if __name__ == "__main__":
    master_host = sys.argv[1]
    master_port = sys.argv[2]
    df = pd.read_parquet('train.parquet', engine='pyarrow')
    img = df.iloc[0]['image']['bytes']
    label = df.iloc[0]['label']
    print('read img label: ', label)
    send_image_to_master(img, master_host, int(master_port))
